package com.arvato.common.solr;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.slf4j.Logger;  
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.arvato.common.config_bean.SolrConfig;
import com.arvato.minipro.bean.bean_dto.common.PageData;

/**
 * 操作solr工具类
 * @author ZHAN655
 *
 */
@Component
@Scope("prototype")
public class SolrUtil{
	
	Logger logger = LoggerFactory.getLogger(this.getClass());

	private HttpSolrClient client = null;
	
	public SolrUtil(){
		client = new HttpSolrClient(SolrConfig.SOLR_URL);
	}
	
	/**
	 * 将map添加到Solr中(单个)
	 * @param map
	 * @return
	 */
	public boolean insert(Map<String, Object> map){
		try{
			SolrInputDocument doc = new SolrInputDocument();
			for(String key : map.keySet()) {
				doc.addField(key, map.get(key));
			}
			client.add(doc);
			UpdateResponse resp = client.commit();
			if(resp.getStatus() == 0) {
				return true;
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}
	
	
	/**
	 * 将mapList添加到Solr中(批量操作)
	 * @param mapList
	 * @return
	 */
	public boolean insert(List<Map<String, Object>> mapList){
		try{
			for(int i = 0; i < mapList.size(); i ++) {
				SolrInputDocument doc = new SolrInputDocument();
				Map<String, Object> mapItem = mapList.get(i);
				for(String key : mapItem.keySet()) {
					doc.addField(key, mapItem.get(key));
				}
				client.add(doc);
				System.out.println(i+"数据");
			}
			
			UpdateResponse resp = client.commit();
			
			if(resp.getStatus() == 0) {
				System.out.println(resp.getStatus());
				return true;
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}
	
	
	
	/**
	 * 更新Solr中的记录(单个)
	 * map中必须含有id才行
	 * @param docMap
	 * @return
	 */
	public boolean update(Map<String,Object> docMap){
		try{
			Object obj = docMap.get("id");
			if(obj == null) {
				return false;
			}
			String id = obj + "";
			SolrInputDocument doc = new SolrInputDocument();
			doc.addField("id", id);
			for(String key : docMap.keySet()){
				if(!"id".equals(key)) {
					Map<String, Object> tempMap = new HashMap<String, Object>();
					tempMap.put("set", docMap.get(key));
					doc.addField(key, tempMap);
				}
			}
			client.add(doc);
			UpdateResponse resp = client.commit();
			if(resp.getStatus() == 0) {
				return true;
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 更新Solr中的记录(批量)
	 * map中必须含有id才行
	 * @param mapList
	 * @return
	 */
	public boolean update(List<Map<String,Object>> mapList){
		try{
			for(int i = 0; i < mapList.size(); i ++) {
				Map<String, Object> mapItem = mapList.get(i);
				Object obj = mapItem.get("id");
				if(obj == null) {
					// 没有ID的 直接跳过
					continue;
				}
				String id = obj + "";
				SolrInputDocument doc = new SolrInputDocument();
				doc.addField("id", id);
				for(String key : mapItem.keySet()){
					if(!"id".equals(key)) {
						Map<String, Object> tempMap = new HashMap<String, Object>();
						tempMap.put("set", mapItem.get(key));
						doc.addField(key, tempMap);
					}
				}
				client.add(doc);
			}
			UpdateResponse resp = client.commit();
			if(resp.getStatus() == 0) {
				return true;
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 通过文档ID删除Solr中的记录
	 * @param id
	 * @return
	 */
	public boolean deleteById(String id)
	{
		try{
			client.deleteById(id);
			UpdateResponse resp = client.commit();
			if(resp.getStatus() == 0)
				return true;
		}catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 根据查询结果 批量删除
	 * @param query
	 * @return
	 */
	public boolean deleteByQuery(String query){
		try{
			client.deleteByQuery(query);
			UpdateResponse resp = client.commit();
			if(resp.getStatus() == 0) {
				return true;
			}
		}catch(Exception e){
			e.printStackTrace();
			logger.error("solr删除出错", e);
		}
		return false;
	}
	
	/**
	 * 查询solr里面的数据
	 * @param query 数据域名称:数据域的值；查询全部*:*；多条件查询 name:Java AND age:20
	 * @param page 页数
	 * @param rows 一页多少条
	 * @return 成功return pageData 失败return null
	 */
	public PageData query(String query,Integer page,Integer rows){
		PageData pageData = new PageData();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		//定义返回自定义数据结构对象
		SolrQuery q = new SolrQuery();
		q.set("q", query);
		q.setStart(page);
		q.setRows(rows);
		try {
			QueryResponse qr = client.query(q);
			SolrDocumentList lst = qr.getResults();
			Long total = qr.getResults().getNumFound();
			// 获取自定义类所有属性名称
			for(SolrDocument doc : lst){
				Set<Entry<String, Object>> entrySet = doc.entrySet();
				Map<String, Object> map = new HashMap<String, Object>();
				for(Entry<String, Object> entry : entrySet) {
					String key = entry.getKey();
					Object value = entry.getValue();
					map.put(key, value);
				}
				list.add(map);
			}
			pageData.setData(list);
			pageData.setTotal(total);
			return pageData;
		} catch (Exception e) {
			logger.error("solr查询出错：" ,e);
			e.printStackTrace();
			return null;
		}
	}
	
	public static void main(String[] args) {
		SolrUtil solr = new SolrUtil();
		PageData pageData = solr.query("name:Java1*", 0, 20);
		System.out.println(pageData.getTotal());
	}
}
